# -*- coding: utf-8 -*-
import sys
import logging
import sqlalchemy
from lxml import etree
from xadmin.model import *
from xadmin.lib.base import *

log = logging.getLogger(__name__)

class ProductrequirementsController(BaseController):
    """REST Controller styled on the Atom Publishing Protocol"""
    # To properly map this controller, ensure your config/routing.py file has
    # a resource setup:
    #     map.resource('productrequirement', 'productrequirements')


    def index(self, format='html'):
        """GET /productrequirements: All items in the collection."""
        # url_for('productrequirements')
        c.requirements = Session.query(ProductRequirement).all()
        response.headers['Content-Type'] = 'text/xml; charset=utf-8'
        return render('/productrequirements/list.mako')

    def listByProject(self, project):
        """GET /:project/productrequirements: All Product Requirements in a project."""
        # url_for('productrequirements_by_project')
        project = Session.query(Project).get(project)
        if project is not None:
            c.requirements = Session.query(ProductRequirement).filter_by(project_id=project.id).all()
            response.headers['Content-Type'] = 'text/xml; charset=utf-8'
            return render('/productrequirements/list.mako')
        else:
            abort(404)

    def create(self):
        """POST /productrequirements: Create a new item."""
        # url_for('productrequirements')
        pass

    def createByProject(self, project):
        project = Session.query(Project).get(project)
        if project is not None:
            content = request.body.read(int(request.environ['CONTENT_LENGTH']))
            if not content:
                content = request.params.get('xml')
            pr = self._createProductRequirement(project.id, content)
            del response.headers['Content-Type']
            response.headers['Location'] = '/%s/productrequirements/%s' % (project.name, pr.id)
            response.status_code = 201
            return
        else:
            abort(404)

    def new(self, format='html'):
        """GET /productrequirements/new: Form to create a new item."""
        # url_for('new_productrequirement')
        c.url = h.url_for('new_productrequirement')
        response.headers['Content-Type'] = 'text/xml; charset=utf-8'
        return render('/productrequirements/form.mako')

    def newByProject(self, project):
        """GET /productrequirements/new: Form to create a new item."""
        # url_for('new_productrequirement_by_project')
        c.project = project
        c.url = h.url_for('create_productrequirements_by_project', project=project)
        response.headers['Content-Type'] = 'text/xml; charset=utf-8'
        return render('/productrequirements/form.mako')

    def update(self, id):
        """PUT /productrequirements/id: Update an existing item."""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(h.url_for('productrequirement', id=ID),
        #           method='put')
        # url_for('productrequirement', id=ID)
        try:
            content = request.body.read(int(request.environ['CONTENT_LENGTH']))
            doc = etree.fromstring(content)
            #Esto es mejor con una validacion del xml
            #if not tree.tag == 'requirement':
            #    abort(400)
            pr = Session.query(ProductRequirement).get(id)
            name = None
            if pr:
                name = doc.xpath('/requirement/name')
                if name:
                    pr.name = name[0].text
                description = doc.xpath('/requirement/description')
                if description:
                    pr.description = description[0].text
                project_id = doc.xpath('/requirement/project')
                if project_id:
                    pr.project_id = project_id[0].text
                priority_id = doc.xpath('/requirement/priority')
                if priority_id:
                    pr.priority_id = priority_id[0].text
                #Session.save(pr)
                Session.commit()
                #del response.headers['Content-Type']
                #response.status_code = 204
                return
            else:
                abort(404)
        except:
            print "ERROR: ", sys.exc_info()[0]
            abort(400)


    def delete(self, id):
        """DELETE /productrequirements/id: Delete an existing item."""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="DELETE" />
        # Or using helpers:
        #    h.form(h.url_for('productrequirement', id=ID),
        #           method='delete')
        # url_for('productrequirement', id=ID)
        pr = Session.query(ProductRequirement).get(id)
        if pr:
            Session.delete(pr)
            Session.commit()
        del response.headers['Content-Type']
        response.status_code = 204
        return

    def show(self, id, format='html'):
        """GET /productrequirements/id: Show a specific item."""
        # url_for('productrequirement', id=ID)
        c.requirement = Session.query(ProductRequirement).get(id)
        if c.requirement:
            response.headers['Content-Type'] = 'text/xml; charset=utf-8'
            return render('/productrequirements/view.mako')
        else:
            abort(404)

    def edit(self, id, format='html'):
        """GET /productrequirements/id;edit: Form to edit an existing item."""
        # url_for('edit_productrequirement', id=ID)
        pass

    def _createProductRequirement(self, project_id, data):
        try:
            project = Session.query(Project).get(project_id)
            if project:
                doc = etree.fromstring(data.encode("utf8"))
                name = doc.xpath('/requirement/name')[0].text
                description = doc.xpath('/requirement/description')[0].text
                priority = doc.xpath('/requirement/priority')[0].text
                pr = ProductRequirement(name, description)
                pr.name = name
                pr.description = description
                pr.priority_id = priority
                project.product_requirements.append(pr)
                Session.save(pr)
                Session.commit()
                return pr
        except:
            print "ERROR: ", sys.exc_info()[0]
            abort(400)